

import '../model/save_info_model.dart';

class HistorySortState {
  final List<SortType> _sortTypes = [
    SortByTime(), SortByName(), SortByStep(), SortByReward(), SortByCost()
  ];
  int _cursor = 0;
  final int _defaultCursor = 0;
  List<SortType> get sortTypes => _sortTypes;
  SortType get currentSortType {
    if (_cursor < _sortTypes.length) {
      return _sortTypes[_cursor];
    }
    return _sortTypes[_defaultCursor];
  }

  void switchType(SortType type) {
    if (_sortTypes.contains(type)) {
      var temp = _sortTypes.indexOf(type);
      if (temp == _cursor) {
        currentSortType.toggleReverse();
      } else {
        _cursor = temp;
      }
    }
    else {
      _cursor = _defaultCursor;
    }
  }

  List<SaveInfo> sort(List<SaveInfo> infos) {
    return currentSortType.sort(infos);
  }
}



class SortByTime extends SortType {
  @override
  final String typeName = "time";

  @override
  bool get reverse => !_reverse;

  @override
  List<SaveInfo> _sort(List<SaveInfo> infos) {
    return infos.toList()..sort((a, b) => a.time.compareTo(b.time));
  }
}

class SortByName extends SortType {
  @override
  final String typeName = "name";

  @override
  List<SaveInfo> _sort(List<SaveInfo> infos) {
    return infos.toList()..sort((a, b) => a.name.compareTo(b.name));
  }
}

class SortByStep extends SortType {
  @override
  final String typeName = "step";

  @override
  bool get reverse => !_reverse;

  @override
  List<SaveInfo> _sort(List<SaveInfo> infos) {
    int parse(String stepIndex) {
      String temp = stepIndex.split("/").first;
      return int.parse(temp);
    }
    return infos.toList()..sort((a, b) => parse(a.stepIndex).compareTo(parse(b.stepIndex)));
  }
}

class SortByReward extends SortType {
  @override
  final String typeName = "reward";

  @override
  bool get reverse => !_reverse;

  @override
  List<SaveInfo> _sort(List<SaveInfo> infos) {
    return infos.toList()..sort((a, b) => a.totalReward.compareTo(b.totalReward));
  }
}

class SortByCost extends SortType {
  @override
  final String typeName = "cost";

  @override
  List<SaveInfo> _sort(List<SaveInfo> infos) {
    return infos.toList()..sort((a, b) => a.totalCost.compareTo(b.totalCost));
  }
}


abstract class SortType {
  bool _reverse = false;
  bool get reverse => _reverse;
  abstract final String typeName;

  void toggleReverse() {
    _reverse = !_reverse;
  }
  List<SaveInfo> _sort(List<SaveInfo> infos);

  List<SaveInfo> sort(List<SaveInfo> infos) {
    if (reverse) {
      return _sort(infos).reversed.toList();
    }
    return _sort(infos);
  }
}